using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using BarCodeDB.Data;
using BarCodeDB.Entities;
using BarCodeDB.Services;

/// <summary>
/// 
/// </summary>
public partial class Admin_MapManager : System.Web.UI.Page
{
    private string _DeCryptedPwd;
    private string _UserName;
    private string _UserDomain;
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.IsInRole("Users"))
        {
            Response.Redirect("~/NoAccess.htm");
        }

        SFG.Common.Utilities.Encryptor _Encryptor = new SFG.Common.Utilities.Encryptor(SFG.Common.Utilities.Encryptor.SymmProvEnum.Rijndael);
        _DeCryptedPwd = _Encryptor.Decrypting(WebConfigurationManager.AppSettings["UserPwd"], WebConfigurationManager.AppSettings["EncryptKey"]);

        _UserName = WebConfigurationManager.AppSettings["UserAcct"];
        _UserDomain = WebConfigurationManager.AppSettings["UserDomain"];
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnProcessFile_Click(object sender, EventArgs e)
    {
        string FilePath = String.Empty;
        
        FilePath = WebConfigurationManager.AppSettings["FileDrop"];
        //SFG.Common.Utilities.Encryptor _Encryptor = new SFG.Common.Utilities.Encryptor(SFG.Common.Utilities.Encryptor.SymmProvEnum.Rijndael);
        //string _DeCryptedPwd = _Encryptor.Decrypting(WebConfigurationManager.AppSettings["UserPwd"], WebConfigurationManager.AppSettings["EncryptKey"]);

        using (new SFG.Common.Utilities.Impersonator(_UserName, _UserDomain, _DeCryptedPwd))
        {
            if (this.FileUpload1.HasFile)
            {
                if (!this.FileUpload1.FileName.EndsWith("xml"))
                {
                    lblMsgBox.Text = "Error... Please select an xml Data file!";
                    return;
                }

                if (!this.FileUpload2.FileName.EndsWith("xslt"))
                {
                    lblMsgBox.Text = "Error... Please select an xslt (Map) file!";
                    return;
                }

                string XmlFilename;
                string XsltFilename;

                GetBaseFileNames(out XmlFilename, out XsltFilename);

                if (XmlFilename == XsltFilename)
                {
                    XmlDocument xmlDoc = ProcessXmlDataFile(FilePath);
                    XmlDocument xsltDoc = ProcessXsltMapFile(FilePath);
                    SaveToDataStore(xsltDoc);

                    Server.Transfer("~/Admin/LaserAppMaps.aspx", false);
                }
                else
                {
                    lblMsgBox.Text = "The file name for the xslt does not match the sample xml file name! Error...";
                }
            }
            else
            {
                lblMsgBox.Text = "No uploaded file. Error...";
            }
        }

        lblMsgBox.Text = "Error... Impersanation account does not have access!";
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="xmlDoc"></param>
    private void SaveToDataStore(XmlDocument xmlDoc)
    {
        String sBuff = xmlDoc.InnerXml;
        String sMsg = String.Empty;

        BarCodeDB.Entities.LaserAppMaps _LaEntity = new BarCodeDB.Entities.LaserAppMaps();
        _LaEntity.FormId = new Guid(this.lblFormID.Text);
        _LaEntity.FormName= this.lblFormType.Text;
        _LaEntity.MajorVer = Convert.ToInt32(this.lblMajV.Text);
        _LaEntity.MinorVer =  Convert.ToInt32(this.lblMinV.Text);
        _LaEntity.FormXml = sBuff;

        BarCodeDB.Services.LaserAppMapsService _LaFormsService = new BarCodeDB.Services.LaserAppMapsService();

        try
        {
            if (_LaFormsService.GetByFormIdMajorVerMinorVer(_LaEntity.FormId, _LaEntity.MajorVer, _LaEntity.MinorVer) == null)
            {
                _LaFormsService.Insert(_LaEntity);
                sMsg = "The FormType: " + this.lblFormType.Text + " - has been added.";
            }
            else
            {
                sMsg = "The FormType: " + this.lblFormType.Text + " - has been updated.";
                _LaFormsService.Update(_LaEntity);
            }
        }
        catch(SystemException se)
        {
            string sMsg1 = se.Message;
        }
        finally
        {
            lblMsgBox.Text = sMsg;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="XmlFilename"></param>
    /// <param name="XsltFilename"></param>
    private void GetBaseFileNames(out string XmlFilename, out string XsltFilename)
    {
        char[] XmlExt = { 'x', 'm', 'l' };
        char[] XsltExt = { 'x', 's', 'l', 't' };

        XmlFilename = this.FileUpload1.FileName.TrimEnd(XmlExt);
        XsltFilename = this.FileUpload2.FileName.TrimEnd(XsltExt);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private XmlDocument ProcessXsltMapFile(string FilePath)
    { 
        XmlDocument xmlDoc = new XmlDocument();
        SFG.Common.Utilities.Encryptor _Encryptor = new SFG.Common.Utilities.Encryptor(SFG.Common.Utilities.Encryptor.SymmProvEnum.Rijndael);

        //string _DeCryptedPwd = _Encryptor.Decrypting(WebConfigurationManager.AppSettings["UserPwd"], WebConfigurationManager.AppSettings["EncryptKey"]);
        using (new SFG.Common.Utilities.Impersonator(_UserName, _UserDomain, _DeCryptedPwd))
        {
            this.FileUpload2.SaveAs(FilePath + "\\" + this.FileUpload2.FileName);
            xmlDoc.Load(FilePath + "\\" + this.FileUpload2.FileName);
        }

        return xmlDoc;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="FilePath"></param>
    /// <returns></returns>
    private XmlDocument ProcessXmlDataFile(string FilePath)
    {   
        XmlDocument xmlDoc = new XmlDocument();
        BarcodeProcessor _AppUtil = new BarcodeProcessor();
        //SFG.Common.Utilities.Encryptor _Encryptor = new SFG.Common.Utilities.Encryptor(SFG.Common.Utilities.Encryptor.SymmProvEnum.Rijndael);
        //string _DeCryptedPwd = _Encryptor.Decrypting(WebConfigurationManager.AppSettings["UserPwd"], WebConfigurationManager.AppSettings["EncryptKey"]);

        using (new SFG.Common.Utilities.Impersonator(_UserName, _UserDomain, _DeCryptedPwd))
        {
            this.FileUpload1.SaveAs(FilePath + "\\" + this.FileUpload1.FileName);
            
            xmlDoc.Load(FilePath + "\\" + this.FileUpload1.FileName);
            _AppUtil.XMLDoc = xmlDoc;

            this.lblFormType.Text = _AppUtil.GetFormName();
            Guid _Guid = _AppUtil.GetFormID();
            this.lblFormID.Text = _Guid.ToString();
            this.lblMajV.Text = _AppUtil.GetMajorVersionNbr();
            this.lblMinV.Text = _AppUtil.GetMinorVersionNbr();

            AppUtil.EncriptXmlDoc(ref xmlDoc);
            xmlDoc.Save(FilePath + "\\" + this.FileUpload1.FileName);
        }

        return xmlDoc;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="_AppUtil"></param>
    /// <param name="_XmlDoc"></param>
    /// <param name="encriptedElement"></param>
    //private void DecriptXmlDoc(ref BarcodeProcessor _AppUtil, ref XmlDocument _XmlDoc, ref XmlElement encriptedElement)
    //{
    //    //Decript        
    //    TripleDESCryptoServiceProvider tDESKey = new TripleDESCryptoServiceProvider();
    //    byte[] _Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
    //    tDESKey.Key = _Key;

    //    EncryptedData encryptedData = new EncryptedData();

    //    encryptedData.Type = EncryptedXml.XmlEncElementUrl;
    //    encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl);

    //    encryptedData.LoadXml(encriptedElement);

    //    EncryptedXml exml = new EncryptedXml();

    //    Byte[] encryptedForm = exml.DecryptData(encryptedData, tDESKey);

    //    exml.ReplaceData(encriptedElement, encryptedForm);

    //    //Display Data
    //    _AppUtil.XMLDoc = _XmlDoc;
    //    Guid _Guid = _AppUtil.GetFormID();
    //}

    /// <summary>
    /// 
    /// </summary>
    /// <param name="xmlDoc"></param>
    //private static void EncriptXmlDoc(ref XmlDocument xmlDoc)
    //{
    //    TripleDESCryptoServiceProvider tDESKey = new TripleDESCryptoServiceProvider();
    //    byte[] _Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
    //    tDESKey.Key = _Key;
    //    XmlElement FormElement = (XmlElement)xmlDoc.SelectSingleNode("/FORM");

    //    EncryptedXml exmlDoc = new EncryptedXml(xmlDoc);
    //    Byte[] encryptedForm = exmlDoc.EncryptData(FormElement, tDESKey, false);

    //    EncryptedData ed = new EncryptedData();
    //    ed.Type = EncryptedXml.XmlEncElementUrl;
    //    ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl);
    //    ed.CipherData = new CipherData();
    //    ed.CipherData.CipherValue = encryptedForm;

    //    EncryptedXml.ReplaceElement(FormElement, ed, false);
    //}
}
